package com.crealth.crmserver;

import java.nio.ByteOrder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.crealth.msg.NetMessageData;


public class CRMServerDecoder extends CumulativeProtocolDecoder {
	/*
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		in.order(ByteOrder.BIG_ENDIAN);
		if (in.prefixedDataAvailable(4)) {
			int bodyLen = in.getInt();			
			//int msgType = in.getInt();
			byte[] msgBody = new byte[bodyLen];
			in.get(msgBody);
			NetMessageData apiMsg = new NetMessageData(bodyLen, msgBody);
			if (apiMsg != null) {
				out.write(apiMsg);
			}
			
			return true;
		}
		return false;
	}
	*/
	
	@Override
    protected boolean doDecode(IoSession session, IoBuffer in,ProtocolDecoderOutput out) 
    		throws Exception {
		in.order(ByteOrder.BIG_ENDIAN);
		while (in.remaining() > 4) {
            //记录解码数据起始位置
            in.mark();
            // 读取包格式及大小
            int bodyLen = in.getInt();          
            // 检查读取的包头是否正常，不正常的话清空buffer
            if (bodyLen < 0) {
                in.clear();
                break;
            } else if (bodyLen > 0 && in.remaining() >= bodyLen) {
            	byte[] msgBody = new byte[bodyLen];
    			in.get(msgBody);
    			NetMessageData apiMsg = new NetMessageData(bodyLen, msgBody);
    			if (apiMsg != null) {
    				out.write(apiMsg);
    			}
                return true;
            } else {    
                // 如果消息包不完整,将指针重新移动消息头的起始位置 
                in.reset();
                return false;
            }
        }
        return false;
    }
	
	
	
	
	

}
